<?php

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\User as UserModel;
use app\api\model\UserAddress;
use app\api\validate\AddressNew;
use app\api\service\Token as TokenService;

class Address extends BaseController
{

    /* 前置校验权限 */
    protected $beforeActionList = [
        'checkPrimayScope' => ['only' => 'createorupdate']
    ];


    /**
     * 
     * @api {POST} /address 新增或更新地址
     * @apiName createOrUpdate
     * @apiGroup Address
     * @apiVersion  1.0.0
     * 
     * 
     * @apiParam  {Number} mobile 手机号
     * @apiParam  {String} province 省
     * @apiParam  {String} city 市
     * @apiParam  {String} country 区
     * @apiParam  {String} detail 详细地址
     * 
     * @apiSuccess (200) {Object} success 写入状态
     * 
     */
    public function createOrUpdate()
    {
        /* 校验参数 */
        $validate = new AddressNew();
        $validate->goCheck();
        /* 获取当前用户 */
        $uid = TokenService::getCurrentUID();
        $user = UserModel::getUserByUID($uid);
        $data = $validate->checkDataVaild(request()->param());
        /* 查询当前用户是否已经填写地址 */
        if(!$user->address){
            $user->address()->save($data);
        }else{
            $user->address->save($data);
        }
        return 'OK';
    }

    /**
     * 
     * @api {GET} /address 获取用户
     * @apiName getAddress
     * @apiGroup Address
     * @apiVersion  1.0.0
     * 
     * 
     * @apiSuccess (200) {Object} address 地址信息
     * 
     */

    public function getAddress()
    {
        $user_id = TokenService::getCurrentUid();
        $address = UserAddress::getUserAddressByUID($user_id);
        return $address;
    }

}
